import React, {Component} from 'react';
import {connect} from 'react-redux';
import {addTodo} from "../actins";

class AddTodo extends Component {
    constructor() {
        super(...arguments);
        this.state = {
            value: ''
        }
    }

    onInputChange = (event) => {
        console.log(event);
        this.setState({
            value: event.target.value
        })
    };

    onSubmit = (ev) => {
        ev.preventDefault();
        const input = this.state.value;
        if (!input.trim()) {
            return;
        }
        this.props.onAdd(input);
        this.setState({value: ''});
    };

    render() {
        return (
            <div className="add-todo">
                <form onSubmit={this.onSubmit}>
                    <input type="text" className="new-todo" onChange={this.onInputChange} value={this.state.value}/>
                    <button className="add-btn" type="submit">
                        添加
                    </button>
                </form>
            </div>
        )
    }
}

const mapDispatchToProps = (dispatch) => (
    {
        onAdd: (text) => {
            dispatch(addTodo(text))
        }
    }
);


export default connect(null, mapDispatchToProps)(AddTodo);